<template>
  <div>
    <v-overlay :value="overlay" style="width:100%;" >
      <img :src="agencyqrurl" width="300px" @click="overlay=false"/>
      <v-subheader style="padding:0;">使用此二维码进行代付</v-subheader>
    </v-overlay>
    <div v-show="!payshow">
      <v-banner single-line>
        结算
      <template v-slot:actions>
        <v-btn text color="#ff6a6a" icon @click="back">
          <v-icon>clear</v-icon>
        </v-btn>
      </template>
      </v-banner>
      <template>
        <v-col cols="12" sm="6" offset-sm="3">
            <v-subheader style="padding:0;">订单详情</v-subheader>
            <v-divider></v-divider>
            <v-list  v-show="ordershow">
              <template>
                <v-list-item>
                  <v-list-item-action>
                    <v-icon size="64">local_mall</v-icon>
                  </v-list-item-action>
                  <v-list-item-content>
                    <v-list-item-title> {{ order.body }} </v-list-item-title>
                    <v-subheader style="padding:0;color:#4caf50"> CNY: {{ order.total_fee/100 }} 元</v-subheader>
                  </v-list-item-content>
                </v-list-item>
              </template>
            </v-list>
            <v-btn @click="selectpay('wechat')" style="margin-top:50px;width:100%" color="success"> 微信支付 </v-btn>
            <v-btn @click="selectpay('agency')" style="margin-top:50px;width:100%" color="error"> 使用代付 </v-btn>
        </v-col>
      </template>
    </div>
    <div class="pa-4 text-center" style="margin-top:15%;" v-show="payshow">
      <v-icon size="128" :color="iconcolor"> {{ icon }}</v-icon>
      <h3 class="title font-weight-light mb-2">{{ title }}</h3>
      <span class="caption grey--text">{{ desc }}</span>
      <v-btn :disabled="pay.done.disabled" :loading="pay.done.loading" v-show="pay.done.show" @click="done" style="margin-top:50px;width:100%" :color="pay.done.color"> {{ pay.done.text }} </v-btn>
      <v-btn :disabled="pay.btn.disabled" :loading="pay.btn.loading" v-show="pay.btn.show" @click="paynow" style="margin-top:50px;width:100%" :color="pay.btn.color"> {{ pay.btn.text }} </v-btn>
    </div>
  </div>
</template>
<script>
import { paymember, wxpayjsapi, domain, wxjssdk, orderstatus } from './../../api/api'
import { OrderInfo } from './../../api/new'

const search = (variable) => {
  var arrStr = window.location.search.substring(1).split("&");
  for (var i = 0; i < arrStr.length; i++) {
    var temp = arrStr[i].split("=");
    if (temp[0] === variable){
        return decodeURIComponent(temp[1]);
    }  
  }
  return (false)
}

export default {
  data: ()=>({
    overlay:false,
    payshow:false,
    ordershow:false,
    icon:'',
    iconcolor:'',
    desc:'',
    title:'正在检查支付环境',
    pay:{
      btn:{
        text:'立即支付',
        show:true,
        color:'success',
        loading:true,
        disabled:false
      },
      done:{
        text:'完成支付',
        show:false,
        color:'success',
        loading:false,
        disabled:false
      }
    },
    agencyqrurl:'',
    order:{
      total_fee:'',
      body:'',
      order_no:''
    }
  }),
  methods: {
    back:function(){
      this.$router.back(-1)
    },
    selectpay:function(spc){
      if(spc == 'wechat'){
        this.payshow = true
      }else if(spc == 'agency'){
        // alert('生成代付')
        var agencyuri = 'https:'+domain + 'pay/agency?order_no='+search("order_no")
        this.agencyqrurl = 'http://www.likehealth.com.cn/qr/?url=https:'+agencyuri
        this.overlay = true
      }
    },
    done:function(){
      if(search('calluri')){
        this.$router.push(search('calluri')+'?order_no='+search("order_no"))
        return
      }
      this.$router.push('/user/center')
    },
    paynow:function(){
      this.pay.btn = {
        text:'立即支付',
        show:true,
        color:'success',
        loading:true,
        disabled:false
      }
      this.$store.commit('setProgress',false)
      const wxPayCall = (res) =>{
          console.log(res)
          if(res.err_msg == "get_brand_wcpay_request:ok" ){
            // res.err_msg 将在用户支付成功后返回ok，但并不保证它绝对可靠。
            fetch(domain+'/api/order/status?order_no='+ search("order_no")+"&hl="+search("hl"), {
              headers: {
                  'authtoken': this.$cookies.get("authtoken"),
              },
              method: 'POST', // *GET, POST, PUT, DELETE, etc.
              mode: 'cors', // no-cors, cors, *same-origin
              redirect: 'follow', // manual, *follow, error
              referrer: 'no-referrer', // *client, no-referrer
            })
            .then((res)=> res.json())
            .then((res)=>{
              if(res.code==1){
                // 支付结果
                this.icon = 'check_circle'; this.iconcolor='success'
                this.pay.btn.show = false
                this.pay.done = {
                  text:'完成支付',
                  show:true,
                  color:'success',
                  loading:false,
                  disabled:false
                }
              }else{
                this.icon = 'error'; this.iconcolor='error'
              }
              this.$store.commit('setAlert',{icon:'close',text: res.msg,show:true})
              this.$store.commit('setProgress',false)
              this.title = res.msg
            })
            .catch((err)=>{
              this.title = err
              this.$store.commit('setAlert',{icon:'close',text:err,show:true})
              this.$store.commit('setProgress',false)
              this.icon = 'error'; this.iconcolor='error'
              // this.icon = 'check_circle'; this.iconcolor='success'
              this.desc = '检查订单状态错误，您可以进入订单列表查看订单状态'
              this.pay.btn = {
                text:'检查订单状态错误',
                show:true,
                color:'success',
                loading:false,
                disabled:true
              }
            })
          }else{
            this.$store.commit('setAlert',{icon:'close',text:'支付失败',show:true})
            this.$store.commit('setProgress',false)
            this.icon = 'error'; this.iconcolor='error'
            this.pay.btn = {
              text:'重新支付',
              show:true,
              color:'success',
              loading:false,
              disabled:false
            }
          }
        }
      wxpayjsapi(search("order_no"),this.$cookies.get("authtoken"),domain+"api/member/order/notify")
      .then((resp)=>{
        var res = resp.data
        this.title = res.err
        this.desc = ''
        if(res.code==1){
          function onBridgeReady(){
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest', {
                "appId":res.data.AppID,     //公众号名称，由商户传入     
                "timeStamp":""+res.data.Timestamp,        //时间戳，自1970年以来的秒数     
                "nonceStr": res.data.NonceStr, //随机串     
                "package":res.data.Package,     
                "signType": res.data.SignType,      //微信签名方式：     
                "paySign": res.data.Sign, //微信签名 
              },
              function(res){
                wxPayCall(res)
              }
              ); 
            }
            if(typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                }else if (document.attachEvent){
                  document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
                  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            }else{
              onBridgeReady();
            }
            
          }else{
            this.pay.btn = {
              text:res.msg,
              show:true,
              color:'success',
              loading:false,
              disabled:true
            }
            this.icon = 'error'; this.iconcolor='error'
            // this.icon = 'check_circle'; this.iconcolor='success'
            this.$store.commit('setAlert',{icon:'close',text:res.err,show:true})
            this.$store.commit('setProgress',false)
          }
      })
      .catch((err)=>{
        this.$store.commit('setAlert',{icon:'close',text:err,show:true})
        this.$store.commit('setProgress',false)
        this.icon = 'error'; this.iconcolor='error'
        // this.icon = 'check_circle'; this.iconcolor='success'
      })
    }
  },
  created: function(){
    OrderInfo(search("order_no"))
    .then((resp)=>{
      var res = resp.data
      if(res.code == 1){
        this.ordershow = true
        this.order = res.data
        if(res.data.status == 2){ // 已支付
          this.icon = 'error'; this.iconcolor='error'
          this.$store.commit('setProgress',false)
          this.title = '订单已支付'
          this.pay.btn = {
            text:'订单已支付',
            show:true,
            color:'success',
            loading:false,
            disabled:true
          }
        }else if(res.data.status == 3) { // 订单已被取消
          this.icon = 'error'; this.iconcolor='error'
          this.$store.commit('setProgress',false)
          this.title = '订单已被取消'
          this.icon = 'error'; this.iconcolor='error'
          this.pay.btn = {
            text:'订单已被取消',
            show:true,
            color:'success',
            loading:false,
            disabled:true
          }
        }else{
          // this.icon = 'more_horiz'; this.iconcolor='success'
          this.$store.commit('setProgress',false)
          this.icon = ''; this.iconcolor='error'
          this.title = res.data.body
          this.desc = '需要支付：'+res.data.total_fee/100+'元'
          this.pay.btn = {
            text:'立即支付',
            show:true,
            color:'success',
            loading:false,
            disabled:false
          }
        }
      }else{
        this.$store.commit('setProgress',false)
        this.icon = 'error'; this.iconcolor='error'
        this.title = res.msg
        this.pay.btn = {
          text:'立即支付',
          show:true,
          color:'success',
          loading:false,
          disabled:true
        }
      }
    })
    .catch((err)=>{
      this.$store.commit('setProgress',false)
      this.icon = 'error'; this.iconcolor='error'
      this.title = res.err
      this.pay.btn = {
        text:'立即支付',
        show:true,
        color:'success',
        loading:false,
        disabled:true
      }
    })
    
  }
}
</script>
<style scoped>
.headinfo {
  color: #00000055;
}
</style>